package com.bobi.tfca.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bobi.tfca.dao.GroupDao;
import com.bobi.tfca.model.constant.ResourcePathConstant;
import com.bobi.tfca.model.entity.*;
import com.bobi.tfca.model.vo.ChatRoom;
import com.bobi.tfca.model.vo.MemberVO;
import com.bobi.tfca.service.*;
import com.bobi.tfca.utils.CosUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 群服务层实现
 *
 * @author 李文发
 * @date 2024/4/3
 */
@Service
@Slf4j
public class GroupServiceImpl extends ServiceImpl<GroupDao, GroupEntity> implements GroupService {

    @Autowired
    private GroupMemberService groupMemberService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private GroupDao groupDao;

    @Autowired
    private GroupMessageService groupMessageService;

    /**
     * 查询全部聊天室
     *
     * @param memberId 会员ID
     * @return 聊天室对象列表
     */
    @Override
    public List<ChatRoom> findAllChatRooms(Integer memberId) {
        List<ChatRoom> chatRoomList = new ArrayList<>();
        // 查询用户的所有群
        LambdaQueryWrapper<GroupMemberEntity> queryWrapper1 = new LambdaQueryWrapper<>();
        List<GroupMemberEntity> list = groupMemberService.list(queryWrapper1.eq(GroupMemberEntity::getMemberId, memberId));
        // 根据id查询所有用户
        for (GroupMemberEntity groupMember : list) {
            ChatRoom chatRoom = new ChatRoom();
            GroupEntity groupEntity = this.getById(groupMember.getGroupId());
            chatRoom.setGroupNum(groupEntity.getGroupNum());
            chatRoom.setGroupId(groupEntity.getGroupId());
            chatRoom.setGroupName(groupEntity.getGroupName());
            chatRoom.setOwnerId(groupEntity.getOwnerId());
            chatRoom.setGroupHead(groupEntity.getGroupHead());

            // 设置未读消息数量 哪些消息没有它，但又是群消息的即是未读
            long count = groupMessageService.getUnReadMessageNum(memberId, groupEntity.getGroupId());
            chatRoom.setUnreadMessages((int) count);
            chatRoomList.add(chatRoom);
        }
        // TODO 这里还可以给ChatRoom整个上次发言时间，来更好的排序
        // 未读消息排序不好，因为当都是0的时候，会一跳一跳的
        // chatRoomList.sort(Comparator.comparing(ChatRoom::getUnreadMessages).reversed());
        return chatRoomList;
    }

    @Override
    public void editGroupName(Integer groupId, String groupName) {
        GroupEntity groupEntity = new GroupEntity();
        groupEntity.setGroupId(groupId);
        groupEntity.setGroupName(groupName);
        this.updateById(groupEntity);
    }

    @Override
    public Boolean disbandGroup(Integer groupId) {
        // 删除聊天信息
        try {
            List<GroupMessageEntity> groupMessageList = groupMessageService.getGroupMessages(groupId);
            groupMessageList.forEach(it -> groupMessageService.removeMessageByMessageId(it.getMessageId()));
            groupMessageService.deleteGroupMessages(groupId);
            // 删除群成员
            groupMemberService.remove(new LambdaQueryWrapper<GroupMemberEntity>().eq(GroupMemberEntity::getGroupId, groupId));
            // 删除群
            this.removeById(groupId);
        } catch (Exception e) {
            log.error("解散群聊失败");
            return false;
        }
        return true;
    }

    @Override
    public Boolean addMember2Group(Integer groupId, List<Integer> choseMemberIdList) {
        List<GroupMemberEntity> list = new ArrayList<>();
        // 添加群员
        choseMemberIdList.forEach(it -> {
            GroupMemberEntity groupMemberEntity = new GroupMemberEntity();
            groupMemberEntity.setMemberId(it);
            groupMemberEntity.setGroupOwner(false);
            groupMemberEntity.setGroupId(groupId);
            list.add(groupMemberEntity);
        });
        try {
            groupMemberService.saveBatch(list);
        } catch (Exception e) {
            log.error("添加成员失败");
            return false;
        }
        // 群人数增加
        this.incrementGroupNum(groupId, list.size());
        return true;
    }


    @Override
    public List<MemberVO> findAllGroupMembers(Integer groupId) {
        List<MemberVO> result = new ArrayList<>();
        List<GroupMemberEntity> list = groupMemberService.list(new LambdaQueryWrapper<GroupMemberEntity>().eq(GroupMemberEntity::getGroupId, groupId));
        HashMap<Integer, String> memberIds = new HashMap<>();
        list.forEach(it -> {
            String role = it.getGroupOwner() ? "群主" : "成员";
            memberIds.put(it.getMemberId(), role);
        });
        List<MemberEntity> memberEntities = memberService.listByIds(memberIds.keySet());
        List<MemberVO> memberVOList = BeanUtil.copyToList(memberEntities, MemberVO.class);
        memberVOList.forEach(it -> it.setRole(memberIds.get(it.getMemberId())));
        return memberVOList;
    }

    @Override
    public Boolean createGroup(Integer groupOwnerId, String groupName, List<Integer> choseMemberIdList) {
        // 创建群对象
        GroupEntity groupEntity = new GroupEntity();
        groupEntity.setGroupName(groupName);
        groupEntity.setOwnerId(groupOwnerId);
        groupEntity.setGroupNum(1);
        try {
            this.save(groupEntity);
            // 保存后得到群ID
            Integer groupId = groupEntity.getGroupId();
            // 保存群主
            GroupMemberEntity groupOwner = new GroupMemberEntity(groupId, groupOwnerId, true);
            groupMemberService.save(groupOwner);
            if (choseMemberIdList != null && choseMemberIdList.size() > 0) {
                List<GroupMemberEntity> groupMemberList = choseMemberIdList.stream().map(it -> new GroupMemberEntity(groupId, it, false)).collect(Collectors.toList());
                groupMemberService.saveBatch(groupMemberList);// 群人数增加
                this.incrementGroupNum(groupEntity.getGroupId(), choseMemberIdList.size());
            }
        } catch (Exception e) {
            log.error("创建群失败");
            return false;
        }
        return true;
    }

    @Override
    public Boolean removeMembers(List<Integer> memberIds, Integer groupId) {
        LambdaQueryWrapper<GroupMemberEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(GroupMemberEntity::getMemberId, memberIds)
                .eq(GroupMemberEntity::getGroupId, groupId);
        groupMemberService.remove(queryWrapper);
        // 群人数减少
        this.incrementGroupNum(groupId, -memberIds.size());
        return true;
    }

    @Override
    public Boolean incrementGroupNum(Integer groupId, int num) {
        groupDao.incrementGroupNum(groupId, num);
        return true;
    }

    /**
     * 默认最多查询12条
     *
     * @param groupId
     * @return
     */
    @Override
    public List<MemberVO> getGroupMemberHeadList(Integer groupId) {
        List<GroupMemberEntity> list = groupMemberService.list(new LambdaQueryWrapper<GroupMemberEntity>().eq(GroupMemberEntity::getGroupId, groupId).last("limit 12"));
        List<Integer> memberIds = new ArrayList<>();
        list.forEach(it -> memberIds.add(it.getMemberId()));
        List<MemberEntity> memberEntities = memberService.listByIds(memberIds);
        return BeanUtil.copyToList(memberEntities, MemberVO.class);
    }

    @Override
    public String changeGroupHead(Integer groupId, MultipartFile file) {
        String url = "";
        try {
            url = CosUtils.uploadFile(file, ResourcePathConstant.IMAGE_PATH);

            GroupEntity groupEntity = new GroupEntity();
            groupEntity.setGroupId(groupId);
            groupEntity.setGroupHead(url);
            this.updateById(groupEntity);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return url;
    }
}
